<template>
  <div class="leave-container">
    <!-- 头部导航 -->
    <header class="header">
      <div class="header-content">
        <h1>📋 请假管理</h1>
        <div class="header-actions">
          <button class="btn-back" @click="$router.push('/home')">🏠 返回首页</button>
          <button class="btn-logout" @click="handleLogout">🚪 退出</button>
        </div>
      </div>
    </header>

    <!-- 主内容 -->
    <main class="main-content">
      <!-- 统计卡片 -->
      <div class="stats-cards" v-if="stats">
        <div class="stat-card">
          <div class="stat-icon">📊</div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.total_count || 0 }}</div>
            <div class="stat-label">总申请数</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">✅</div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.approved_days || 0 }}</div>
            <div class="stat-label">已批准天数</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">⏳</div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.pending_count || 0 }}</div>
            <div class="stat-label">待审批</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">❌</div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.rejected_count || 0 }}</div>
            <div class="stat-label">已拒绝</div>
          </div>
        </div>
      </div>

      <!-- 操作栏 -->
      <div class="action-bar">
        <button class="btn-primary" @click="showSubmitDialog">➕ 提交请假申请</button>
        <div class="filter-group">
          <select v-model="filterStatus" @change="loadLeaveList">
            <option value="">全部状态</option>
            <option value="pending">待审批</option>
            <option value="approved">已通过</option>
            <option value="rejected">已拒绝</option>
            <option value="cancelled">已取消</option>
          </select>
          <button class="btn-secondary" @click="loadStats">🔄 刷新统计</button>
        </div>
      </div>

      <!-- 请假列表 -->
      <div class="leave-list">
        <div v-if="loading" class="loading">⏳ 加载中...</div>
        
        <div v-else-if="leaveRequests.length === 0" class="empty">
          <p>暂无请假记录</p>
        </div>
        
        <div v-else class="leave-table">
          <table>
            <thead>
              <tr>
                <th>申请人</th>
                <th>部门</th>
                <th>请假类型</th>
                <th>开始日期</th>
                <th>结束日期</th>
                <th>天数</th>
                <th>状态</th>
                <th>申请时间</th>
                <th v-if="userRole !== 'employee'">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="leave in leaveRequests" :key="leave.id" :class="'status-' + leave.status">
                <td>
                  <div class="user-cell">
                    <div class="user-avatar">{{ leave.user_name[0] }}</div>
                    <div>
                      <div class="user-name">{{ leave.user_name }}</div>
                      <div class="user-account">@{{ leave.user_account }}</div>
                    </div>
                  </div>
                </td>
                <td>{{ leave.department_name }}</td>
                <td>
                  <span class="leave-type-badge" :class="'type-' + leave.leave_type">
                    {{ leave.leave_type_name }}
                  </span>
                </td>
                <td>{{ leave.start_date }}</td>
                <td>{{ leave.end_date }}</td>
                <td><strong>{{ leave.days }}</strong> 天</td>
                <td>
                  <span class="status-badge" :class="'status-' + leave.status">
                    {{ leave.status_name }}
                  </span>
                </td>
                <td>{{ formatDateTime(leave.created_at) }}</td>
                <td v-if="userRole !== 'employee'" class="action-cell">
                  <button 
                    v-if="leave.status === 'pending' && canApprove(leave)"
                    class="btn-sm btn-approve" 
                    @click="showApproveDialog(leave, 'approve')"
                  >
                    ✅ 通过
                  </button>
                  <button 
                    v-if="leave.status === 'pending' && canApprove(leave)"
                    class="btn-sm btn-reject" 
                    @click="showApproveDialog(leave, 'reject')"
                  >
                    ❌ 拒绝
                  </button>
                  <button 
                    class="btn-sm btn-detail" 
                    @click="showDetailDialog(leave)"
                  >
                    👁️ 详情
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </main>

    <!-- 提交请假对话框 -->
    <div v-if="showSubmitForm" class="dialog-overlay" @click.self="closeSubmitDialog">
      <div class="dialog">
        <div class="dialog-header">
          <h3>➕ 提交请假申请</h3>
          <button class="btn-close" @click="closeSubmitDialog">✕</button>
        </div>
        
        <div class="dialog-body">
          <div class="form-group">
            <label>请假类型 *</label>
            <select v-model="submitForm.leave_type">
              <option value="">请选择</option>
              <option value="sick">病假</option>
              <option value="personal">事假</option>
              <option value="annual">年假</option>
              <option value="maternity">产假</option>
              <option value="other">其他</option>
            </select>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>开始日期 *</label>
              <input v-model="submitForm.start_date" type="date">
            </div>
            <div class="form-group">
              <label>结束日期 *</label>
              <input v-model="submitForm.end_date" type="date">
            </div>
          </div>
          
          <div class="form-group">
            <label>请假天数 *</label>
            <input v-model="submitForm.days" type="number" step="0.5" min="0.5" placeholder="支持半天，如：0.5、1、1.5">
          </div>
          
          <div class="form-group">
            <label>请假原因 *</label>
            <textarea v-model="submitForm.reason" rows="4" placeholder="请详细说明请假原因"></textarea>
          </div>
        </div>
        
        <div class="dialog-footer">
          <button class="btn-secondary" @click="closeSubmitDialog">取消</button>
          <button class="btn-primary" @click="handleSubmit" :disabled="submitting">
            {{ submitting ? '⏳ 提交中...' : '✅ 提交申请' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 审批对话框 -->
    <div v-if="showApprovalForm" class="dialog-overlay" @click.self="closeApproveDialog">
      <div class="dialog">
        <div class="dialog-header">
          <h3>{{ approvalAction === 'approve' ? '✅ 审批通过' : '❌ 审批拒绝' }}</h3>
          <button class="btn-close" @click="closeApproveDialog">✕</button>
        </div>
        
        <div class="dialog-body">
          <div class="approval-info">
            <p><strong>申请人：</strong>{{ currentLeave?.user_name }}</p>
            <p><strong>请假类型：</strong>{{ currentLeave?.leave_type_name }}</p>
            <p><strong>请假时间：</strong>{{ currentLeave?.start_date }} 至 {{ currentLeave?.end_date }}</p>
            <p><strong>请假天数：</strong>{{ currentLeave?.days }} 天</p>
            <p><strong>请假原因：</strong>{{ currentLeave?.reason }}</p>
          </div>
          
          <div class="form-group">
            <label>审批意见</label>
            <textarea v-model="approvalForm.comment" rows="3" placeholder="请填写审批意见（可选）"></textarea>
          </div>
        </div>
        
        <div class="dialog-footer">
          <button class="btn-secondary" @click="closeApproveDialog">取消</button>
          <button 
            :class="approvalAction === 'approve' ? 'btn-primary' : 'btn-danger'" 
            @click="handleApprove" 
            :disabled="submitting"
          >
            {{ submitting ? '⏳ 处理中...' : (approvalAction === 'approve' ? '✅ 确认通过' : '❌ 确认拒绝') }}
          </button>
        </div>
      </div>
    </div>

    <!-- 详情对话框 -->
    <div v-if="showDetail" class="dialog-overlay" @click.self="closeDetailDialog">
      <div class="dialog">
        <div class="dialog-header">
          <h3>📋 请假详情</h3>
          <button class="btn-close" @click="closeDetailDialog">✕</button>
        </div>
        
        <div class="dialog-body" v-if="currentLeave">
          <div class="detail-section">
            <h4>申请信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">申请人：</span>
                <span>{{ currentLeave.user_name }} (@{{ currentLeave.user_account }})</span>
              </div>
              <div class="detail-item">
                <span class="label">所属部门：</span>
                <span>{{ currentLeave.department_name }}</span>
              </div>
              <div class="detail-item">
                <span class="label">请假类型：</span>
                <span class="leave-type-badge" :class="'type-' + currentLeave.leave_type">
                  {{ currentLeave.leave_type_name }}
                </span>
              </div>
              <div class="detail-item">
                <span class="label">请假时间：</span>
                <span>{{ currentLeave.start_date }} 至 {{ currentLeave.end_date }}</span>
              </div>
              <div class="detail-item">
                <span class="label">请假天数：</span>
                <span><strong>{{ currentLeave.days }}</strong> 天</span>
              </div>
              <div class="detail-item">
                <span class="label">申请时间：</span>
                <span>{{ currentLeave.created_at }}</span>
              </div>
              <div class="detail-item full-width">
                <span class="label">请假原因：</span>
                <p class="reason-text">{{ currentLeave.reason }}</p>
              </div>
            </div>
          </div>
          
          <div class="detail-section" v-if="currentLeave.status !== 'pending' && currentLeave.status !== 'cancelled'">
            <h4>审批信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">审批状态：</span>
                <span class="status-badge" :class="'status-' + currentLeave.status">
                  {{ currentLeave.status_name }}
                </span>
              </div>
              <div class="detail-item">
                <span class="label">审批人：</span>
                <span>{{ currentLeave.approver_name || '未知' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">审批时间：</span>
                <span>{{ currentLeave.approved_at || '未审批' }}</span>
              </div>
              <div class="detail-item full-width" v-if="currentLeave.approval_comment">
                <span class="label">审批意见：</span>
                <p class="reason-text">{{ currentLeave.approval_comment }}</p>
              </div>
            </div>
          </div>
        </div>
        
        <div class="dialog-footer">
          <button class="btn-primary" @click="closeDetailDialog">关闭</button>
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <div v-if="message" :class="['toast', messageType]">{{ message }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import request from '../utils/request.js'

const router = useRouter()

// 状态
const userRole = ref(localStorage.getItem('user_role') || 'employee')
const currentUserId = ref(parseInt(localStorage.getItem('user_id')))
const leaveRequests = ref([])
const stats = ref(null)
const loading = ref(false)
const filterStatus = ref('')

// 对话框状态
const showSubmitForm = ref(false)
const showApprovalForm = ref(false)
const showDetail = ref(false)
const submitting = ref(false)
const message = ref('')
const messageType = ref('info')
const currentLeave = ref(null)
const approvalAction = ref('approve')

// 表单数据
const submitForm = ref({
  leave_type: '',
  start_date: '',
  end_date: '',
  days: '',
  reason: ''
})

const approvalForm = ref({
  comment: ''
})

onMounted(() => {
  loadLeaveList()
  loadStats()
})

// 加载请假列表
const loadLeaveList = async () => {
  loading.value = true
  try {
    let url = '/leave/list'
    const params = []
    if (filterStatus.value) {
      params.push(`status=${filterStatus.value}`)
    }
    if (params.length > 0) {
      url += '?' + params.join('&')
    }
    
    const res = await request.get(url)
    if (res.data.code === 200) {
      leaveRequests.value = res.data.data.leave_requests
    }
  } catch (error) {
    console.error('加载请假列表失败:', error)
    showToast('加载请假列表失败', 'error')
  } finally {
    loading.value = false
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    const res = await request.get('/leave/stats/personal')
    if (res.data.code === 200) {
      stats.value = res.data.data
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 显示提交对话框
const showSubmitDialog = () => {
  submitForm.value = {
    leave_type: '',
    start_date: '',
    end_date: '',
    days: '',
    reason: ''
  }
  showSubmitForm.value = true
}

// 关闭提交对话框
const closeSubmitDialog = () => {
  showSubmitForm.value = false
}

// 提交请假申请
const handleSubmit = async () => {
  if (!submitForm.value.leave_type || !submitForm.value.start_date || 
      !submitForm.value.end_date || !submitForm.value.days || !submitForm.value.reason) {
    showToast('请填写完整的请假信息', 'error')
    return
  }
  
  submitting.value = true
  try {
    const res = await request.post('/leave/submit', submitForm.value)
    if (res.data.code === 200) {
      showToast('请假申请提交成功', 'success')
      closeSubmitDialog()
      loadLeaveList()
      loadStats()
    }
  } catch (error) {
    showToast(error.response?.data?.message || '提交失败', 'error')
  } finally {
    submitting.value = false
  }
}

// 显示审批对话框
const showApproveDialog = (leave, action) => {
  currentLeave.value = leave
  approvalAction.value = action
  approvalForm.value = { comment: '' }
  showApprovalForm.value = true
}

// 关闭审批对话框
const closeApproveDialog = () => {
  showApprovalForm.value = false
  currentLeave.value = null
}

// 处理审批
const handleApprove = async () => {
  submitting.value = true
  try {
    const res = await request.post(`/leave/approve/${currentLeave.value.id}`, {
      action: approvalAction.value,
      comment: approvalForm.value.comment
    })
    if (res.data.code === 200) {
      showToast(`审批${approvalAction.value === 'approve' ? '通过' : '拒绝'}成功`, 'success')
      closeApproveDialog()
      loadLeaveList()
    }
  } catch (error) {
    showToast(error.response?.data?.message || '审批失败', 'error')
  } finally {
    submitting.value = false
  }
}

// 显示详情对话框
const showDetailDialog = (leave) => {
  currentLeave.value = leave
  showDetail.value = true
}

// 关闭详情对话框
const closeDetailDialog = () => {
  showDetail.value = false
  currentLeave.value = null
}

// 判断是否可以审批
const canApprove = (leave) => {
  if (userRole.value === 'admin') return true
  if (userRole.value === 'manager' && leave.user_id !== currentUserId.value) return true
  return false
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return datetime.split(' ')[0]
}

// 退出登录
const handleLogout = async () => {
  if (!confirm('确定要退出登录吗？')) return
  
  try {
    await request.post('/user/logout')
  } catch (error) {
    console.error('退出失败:', error)
  } finally {
    localStorage.clear()
    router.push('/')
  }
}

// 显示提示消息
const showToast = (msg, type = 'info') => {
  message.value = msg
  messageType.value = type
  setTimeout(() => {
    message.value = ''
  }, 3000)
}
</script>

<style scoped>
.leave-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.header {
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px 0;
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h1 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.btn-back, .btn-logout {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: transform 0.2s;
}

.btn-back {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.btn-logout {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.btn-back:hover, .btn-logout:hover {
  transform: translateY(-2px);
}

.main-content {
  max-width: 1400px;
  margin: 20px auto;
  padding: 0 20px;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  font-size: 40px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

/* 操作栏 */
.action-bar {
  background: white;
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-group {
  display: flex;
  gap: 12px;
}

.filter-group select {
  padding: 10px 16px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
}

.btn-primary, .btn-secondary {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: transform 0.2s;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.btn-secondary {
  background: #f0f0f0;
  color: #333;
}

.btn-primary:hover, .btn-secondary:hover {
  transform: translateY(-2px);
}

/* 请假列表 */
.leave-list {
  background: white;
  padding: 20px;
  border-radius: 12px;
  min-height: 400px;
}

.loading, .empty {
  text-align: center;
  padding: 60px 20px;
  color: #999;
  font-size: 16px;
}

.leave-table {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

thead {
  background: #f8f9fa;
}

th {
  padding: 12px;
  text-align: left;
  font-weight: 600;
  color: #555;
  border-bottom: 2px solid #e0e0e0;
}

td {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.user-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.user-name {
  font-weight: 600;
  color: #333;
}

.user-account {
  font-size: 12px;
  color: #999;
}

.leave-type-badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.type-sick { background: #ffe5e5; color: #d63031; }
.type-personal { background: #e3f2fd; color: #1976d2; }
.type-annual { background: #e8f5e9; color: #388e3c; }
.type-maternity { background: #f3e5f5; color: #7b1fa2; }
.type-other { background: #fafafa; color: #666; }

.status-badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.status-pending { background: #fff3cd; color: #856404; }
.status-approved { background: #d4edda; color: #155724; }
.status-rejected { background: #f8d7da; color: #721c24; }
.status-cancelled { background: #f0f0f0; color: #666; }

.action-cell {
  display: flex;
  gap: 8px;
}

.btn-sm {
  padding: 6px 12px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 600;
  transition: transform 0.2s;
}

.btn-approve { background: #28a745; color: white; }
.btn-reject { background: #dc3545; color: white; }
.btn-detail { background: #667eea; color: white; }
.btn-sm:hover { transform: translateY(-2px); }

/* 对话框 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 16px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow: auto;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.dialog-header h3 {
  margin: 0;
  font-size: 20px;
}

.btn-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.dialog-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 16px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #555;
  font-size: 14px;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 10px 12px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  box-sizing: border-box;
  font-family: inherit;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #e0e0e0;
}

.btn-danger {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
}

.approval-info {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.approval-info p {
  margin: 8px 0;
  color: #333;
}

/* 详情样式 */
.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  border-bottom: 2px solid #667eea;
  padding-bottom: 8px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-item.full-width {
  grid-column: 1 / -1;
}

.detail-item .label {
  font-weight: 600;
  color: #666;
  font-size: 13px;
}

.reason-text {
  margin: 8px 0 0 0;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  line-height: 1.6;
  color: #333;
}

/* Toast消息 */
.toast {
  position: fixed;
  top: 80px;
  right: 20px;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  animation: slideIn 0.3s ease-out;
  z-index: 1001;
}

@keyframes slideIn {
  from {
    transform: translateX(400px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.toast.success {
  background: #d4edda;
  color: #155724;
}

.toast.error {
  background: #f8d7da;
  color: #721c24;
}
</style>

